'''
Author: mypx
Date: 2025-10-21 15:29:15
LastEditTime: 2025-10-21 15:32:59
LastEditors: mypx mypx_coder@163.com
Description: 
'''
# 依赖条件模块
from typing import Dict, List
from ..container_modules.config_container import ConfigContainerModule
from parser.config_model import ConfigItem, Condition
from parser.expression_evaluator import ExpressionEvaluator


class DependencyModule:
    """依赖条件模块"""

    def __init__(self, config_container_module: ConfigContainerModule):
        self.config_container_module = config_container_module
        self.expression_evaluator = ExpressionEvaluator()
        self.dependencies: Dict[str, List[Condition]] = {}  # {config_id: [conditions]}

    def register_dependency(self, config_item: ConfigItem) -> None:
        """注册配置项的依赖条件"""
        if config_item.properties.depends_on:
            self.dependencies[config_item.id] = [config_item.properties.depends_on]

    def check_dependency(self, config_id: str, config_values: Dict[str, any]) -> bool:
        """检查配置项的依赖条件"""
        conditions = self.dependencies.get(config_id)
        if not conditions:
            return True  # 没有依赖条件，默认为满足

        for condition in conditions:
            # 计算条件表达式
            condition.evaluated = self.expression_evaluator.evaluate(
                condition.expression, config_values
            )
            if not condition.evaluated:
                return False

        return True

    def update_dependency_states(
        self, config_items: List[ConfigItem], config_values: Dict[str, any]
    ) -> None:
        """更新所有配置项的依赖状态"""
        for config_item in config_items:
            is_dependent = self.check_dependency(config_item.id, config_values)
            config_item.is_enabled = is_dependent
            self.config_container_module.set_container_enabled(
                config_item.id, is_dependent
            )
